import {Component, Input, OnInit, TemplateRef} from "@angular/core";
import {NzDrawerRef, NzDrawerService, NzMessageService} from "ng-zorro-antd";
import {I18NService} from "@core/i18n/i18n.service";
import {MenuService} from "../menu/services/menu.service";
import {FormBuilder, FormGroup} from "@angular/forms";
import {PopupService} from "@shared/popup/popup.service";
import {Router} from "@angular/router";
import {Observable} from "rxjs";
import {HttpClient} from "@angular/common/http";
import { saveAs } from 'file-saver';
import {ViewChild} from "@angular/core";
import {PaperService} from "./service/paper.service";

@Component({
  styles: [],
  templateUrl: './paper-list.html'
})
export class PaperListComponent implements OnInit {
  @ViewChild('drawerTemplate') drawerTemplate: TemplateRef<{
    $implicit: { value: string };
    drawerRef: NzDrawerRef<any>;
  }>;
  constructor(
    private message: NzMessageService,
    private i18nService: I18NService,
    private fb: FormBuilder,
    private popupService: PopupService,
    private paperService: PaperService,
    private router:Router,
    private http: HttpClient,
    private drawerService: NzDrawerService
  ) {
    this.validateForm = this.fb.group({
      questionType:'所有题型',
      content:null
    });
  }
  page = {
    pageNo: 1,
    pageSize: 10,
    total: 1
  };
  _loading = false;
  validateForm: FormGroup;
  questionByTypeList=['所有题型','单选题','多选题','判断题','填空题','解答题','编程题'];
  mapOfExpandData: { [key: string]: boolean } = {};
  listOfData = [];
  ngOnInit(): void {
    this.getAllPaperByPage(true);
  }
  goInsert(){
    this.router.navigateByUrl('/main/question/questionInsert');
  }

  submit(){}


  getQuestionByType(e):void{
    this.getAllPaperByPage(true);
  }

  // showModify(item?: any): void {
  //
  //   if (item !== undefined) {
  //     let params = {
  //       id: item.id
  //     };
  //     let title = '试题修改';
  //     this.popupService.create({
  //       title: title,
  //       content: QuestionModifyComponent,
  //       componentParams: params,
  //       width: 1000,
  //       onSubmit: (res) => {
  //         this.getAllQuestionByPage(true);
  //       },
  //       onCancel: (res) => { }
  //     }).afterClose.subscribe(res => { });
  //   }else{
  //     this.router.navigateByUrl('/main/question/questionModify');
  //   }
  //
  // }


  private getDisposition(data: string) {
    const arr: any = (data || '')
      .split(';')
      .filter(i => i.includes('='))
      .map(v => {
        const strArr = v.split('=');
        const utfId = `UTF-8''`;
        let value = strArr[1];
        if (value.startsWith(utfId)) {
          value = value.substr(utfId.length);
        }
        return { [strArr[0].trim()]: value };
      });
    return arr.reduce((o, item: any) => item, {});
  }


  getAllPaperByPage(reset = false):  void {
    if (reset) {
      this.page.pageNo = 1;
    }
    if (!this._loading) {
      this._loading = true;
      this.paperService.getAllPaperByPage(this.page.pageNo, this.page.pageSize)
        .subscribe(res => {
          this.listOfData = res.records;
          this.page.total = res.total;
          this._loading = false;
        }, err => {
          this._loading = false;
          this.listOfData = [];
        });
    }
  }

  // delete(id: number) {
  //   this.questionService.deltetQuestion(id)
  //     .subscribe(res => {
  //       if (res) {
  //         this.message.success(this.i18nService.translate('modify.return.delete_success'));
  //         this.getAllQuestionByPage();
  //       } else {
  //         this.message.error(this.i18nService.translate('modify.return.delete_error'));
  //       }
  //     });
  // }

  search():void{
    // this.getAllQuestionByPage(true);
  }

  exportQuestionByIds(idStr:string):void {
    this.http.get( '/get/web/download/questionModule/QuestionService/exportQuestionByIds', {responseType:'blob',observe:'response',params:{idStr}})
      .subscribe(res => {
        if (res.status !== 200 || res.body.size <= 0) {
          this.message.error(this.i18nService.translate('导出失败'));
          return;
        }
        const name=res.headers.get('Content-disposition');
        const disposition: any = this.getDisposition(name);
        const fileName =
          disposition[`filename*`] ||
          disposition[`filename`] ||
          res.headers.get('filename') ||
          res.headers.get('x-filename');
        saveAs(res.body, decodeURI(fileName));
        this.message.success(this.i18nService.translate('导出成功'));
      }, err => {
        this.message.error(this.i18nService.translate('导出失败'));
      });
  }

}

